<template>
	<view class="container">
		<view class="a">
			<view class="search">
				<icon type="search" size="16" color="#999" />
				<view class="uni-flex-item"><input type="text" class="uni-input" placeholder="输入关键字进行搜索" />
				</view>
			</view>
		</view>
		<scroll-view class="tab" scroll-x="true" croll-x="true" scroll-with-animation :scroll-left="familyLeft">
			<block v-for="(item, index) in familyList" :key="index">
				<text :class="['', active == index ? 'on' : '']"
					@click="familyClick(index, item.dictId)">{{item.dictName}}</text>
			</block>
		</scroll-view>
		<view v-if="list.length > 0">
			<view class="bd">
				<navigator hover-class="none" class="product_list"
					v-for="(item, index) in list" :key="index"
					:url="'/pages/goods/goods_detail/index?productId='+item.productId + '&type=SALE'">
				<!-- <view v-for="(item, index) in list" :key="index"> -->
					<view class="box">
						<image mode="aspectFill" :src="item.productImage || '../../static/images/defalut_avatar'" class="pic"></image>
						<view class="dl">
							<view class="dt line1">{{item.productName}}</view>
							<!-- <view class="p">库存20件</view> -->
							<view class="uni-flex">
								<view class="uni-flex-item">￥<text>{{item.proxyPrice || 0.00}}</text></view>
								<view style="padding-left: 10rpx;" @click="joinCart(item.productId)">
									<image mode="aspectFill" src="../../../static/images/car.png"></image>
								</view>
							</view>
						</view>
					</view>
				</navigator>
				<!-- </view> -->
			</view>
		</view>
		<u-empty marginTop="100" v-else mode="favor" icon="../../../../static/images/list.png" text="暂无产品" width="320"
			height="320" textSize="24"></u-empty>
		<view class="bottom">
			<view class="uni-inline-item">
				<image mode="widthFix" src="@/static/images/car.png"></image>
				<view class="uni-flex-item">
					<view>已采购{{CartCount}}件商品</view>
					<view class="price">¥{{CartPrice}}</view>
				</view>
				<button v-if="!isOpen" type="primary" size="mini" @click="subOrder">提交订单</button>
				<button v-else type="primary" size="mini" @click="addCart(false)">确认</button>
			</view>
		</view>
		
		<productWindow :attr="attr" :isShow="0" :iSplus="1" @myevent="onMyEvent" @ChangeAttr="ChangeAttr"
			@ChangeCartNum="ChangeCartNum" @attrVal="attrVal" @iptCartNum="iptCartNum" id="product-window"
			@getImg="showImg"></productWindow>
	</view>
</template>


<script>
	import {
		mapGetters
	} from "vuex";
	import {
		getClassification,
		getList,
		getUpSupplier,
		getFamily
	} from '@/api/product.js';
	import {
		toLogin
	} from "@/libs/login.js";
	import {
		getDetail
	} from "@/api/product.js";
	import {
		getUserCar,
		addToCar
	} from "@/api/order.js";
	import productWindow from "@/components/productWindow";
	export default {
		data() {
			return {
				tabClick: 0,
				tabList: [],
				familyList: [],
				list: [],
				familyLeft: 0,
				active: 0,
				isWidth: 0,
				attr: {
					cartAttr: false,
					productAttr: [],
					productSelect: {},
				},
				attrValue: "", //已选属性
				isOpen: false, //是否打开属性组件
				cart_num: 1, //购买数量
				productValue: [], //系统属性
				attrTxt: '请选择',
				CartCount: 0,
				CartPrice: 0,
				selectValue: []
			}

		},
		components: {
			productWindow
		},
		computed: {
			...mapGetters({
				isLogin: 'isLogin',
				uid: 'uid',
				userType: 'userType',
			})
		},
		watch: {
			isLogin: {
				handler: function(newV, oldV) {
					if (newV == true) {
						this.getProductCategory()
					}
				},
				deep: true,
			},
		},
		onLoad() {
			let that = this;
			that.getProductCategory();
			that.getUserCar();
		},

		onShow() {


		},

		methods: {
			/**
			 * 导航点击
			 * @param {Object} index
			 * @param {Object} dictId
			 */
			longClick(index, dictId) {
				let that = this;
				that.tabClick = index;
				that.active = 0;
				that.pid = dictId;
				that.getFamily(dictId);
			},

			/**
			 * 
			 * 获取产品默认分类
			 */
			getProductCategory() {
				let that = this;
				getClassification().then(res => {
					that.tabList = res.value;
					that.getFamily(res.value[that.tabClick].dictId);
					that.loading = false;
				}).catch(err => {
					that.$util.Tips({
						title: err
					})
				})
			},

			/**
			 * 获取产品系列
			 * @param {int}  dictId
			 */
			getFamily(dictId) {
				let that = this;
				getFamily({
					classification: dictId
				}).then(res => {
					that.familyList = res.value;
					that.getProductList(dictId, res.value[that.active].dictId)
				}).catch(err => {
					that.$util.Tips({
						title: err
					})
				})
			},

			/* 系类点击
			 * @param {int}  index
			 * @param {int}  dictId
			 */
			familyClick(index, dictId) {
				let that = this;
				that.active = index;
				if (that.familyList.length > 2) {
					that.familyLeft = (index - 2) * that.isWidth;
				}
				that.getProductList(that.tabList[that.tabClick].dictId, dictId);
			},

			/**
			 * 获取产品列表
			 * @param {int}  dictId
			 */
			getProductList(pid, dictId) {
				let that = this;
				getList({
					// parentId: dictId,
					family: dictId,
					classification: pid
				}).then(res => {
					that.list = res.value.list;
				}).catch(err => {
					that.$util.Tips({
						title: err
					})
				})
			},
			
			/**
			 * 获取产品详情
			 * @@param {int} productId  
			 */
			getProdcutDetail(productId) {
				let that = this;
				getDetail({
					productId: productId
				}).then(res => {
			
					that.detail = res.value;
					that.swiperList = [].concat(res.value.productImage);
					that.$set(that, "productValue", res.value.specificationList);
			
					let attr = [],
						attr_value = [],
						attr_values = [],
						list = res.value.specificationList;
					list.forEach((e, i) => {
						attr_value.push({
							attr: e.specifications,
							check: false
						});
						attr_values[i] = e.specifications;
					})
					attr.push({
						attr_value: attr_value,
						attr_values: attr_values,
						productId: that.detail.productId
					})
					that.$set(that.attr, "productAttr", attr);
			
					// 获取用户的购物车
					if (that.isLogin) {
						that.getUserCar();
					}
					// 默认选择规格de
					that.defaultSelect();
					that.addCart();
				}).catch(err => {
					that.$util.Tips({
						title: err
					});
				})
			},
			
			/*
			 * 弹框关闭
			 */
			onMyEvent: function() {
				this.$set(this.attr, "cartAttr", false);
				this.$set(this, "isOpen", false);
			},
			
			/**
			 * 属性变动赋值
			 */
			ChangeAttr: function(res) {
				let index = this.productValue.findIndex((e) => {
					return e.specifications == res
				});
				let productSelect = this.productValue[index];
				if (!productSelect) {
					this.$util.Tips({
						title: "暂无该产品,重新选择",
						success: () => {
							this.a = true
							this.attr.productSelect.cart_num = 0
						},
					});
				} else {
					this.a = false
				}
				// this.$set(this, "selectSku", productSelect);
				if (productSelect) {
					this.$set(this.attr.productSelect, "image", productSelect.productImage);
					this.$set(this.attr.productSelect, "price", productSelect.proxyPrice);
					// if (this.userType == 'STORE') {
					// 	this.$set(this.attr.productSelect, "price", productSelect.productPrice);
					// } else if(this.userType == 'SALE') {
					// 	this.$set(this.attr.productSelect, "price", productSelect.proxyPrice);
					// }
					this.$set(this.attr.productSelect, "cart_num", 1);
					this.$set(this, "attrValue", index);
					this.$set(this, "attrTxt", "已选择");
				} else {
					this.$set(this.attr.productSelect, "image", productSelect.productImage);
					this.$set(this.attr.productSelect, "price", productSelect.proxyPrice);
					// if (this.userType == 'STORE') {
					// 	this.$set(this.attr.productSelect, "price", productSelect.productPrice);
					// } else if(this.userType == 'SALE') {
					// 	this.$set(this.attr.productSelect, "price", productSelect.proxyPrice);
					// }
					this.$set(this.attr.productSelect, "cart_num", 0);
					this.$set(this, "attrValue", "");
					this.$set(this, "attrTxt", "请选择");
				}
			},
			
			/**
			 * 购物车数量加和数量减
			 */
			ChangeCartNum: function(changeValue) {
				//changeValue:是否 加|减
				//获取当前变动属性
				let productSelect = this.productValue[this.attrValue];
				//如果没有属性,赋值给商品默认库存
				if (productSelect === undefined && !this.attr.productAttr.length)
					productSelect = this.attr.productSelect;
				//无属性值即库存为0；不存在加减；
				if (productSelect === undefined) return;
				let stock = productSelect.stock || 0;
				let num = this.attr.productSelect;
				if (changeValue) {
					num.cart_num++;
					// if (num.cart_num > stock) {
					// 	this.$set(this.attr.productSelect, "cart_num", stock ? stock : 1);
					// 	this.$set(this, "cart_num", stock ? stock : 1);
					// }
				} else {
					num.cart_num--;
					// if (num.cart_num < 1) {
					// 	this.$set(this.attr.productSelect, "cart_num", 1);
					// 	this.$set(this, "cart_num", 1);
					// }
				}
			},
			
			/**
			 * @param {Object} val
			 * 规格赋值
			 */
			attrVal(val) {
				this.$set(
					this.attr.productAttr[val.indexw],
					"index",
					this.attr.productAttr[val.indexw].attr_values[val.indexn]
				);
			},
			
			/**
			 * 购物车手动填写
			 */
			iptCartNum: function(e) {
				this.$set(this.attr.productSelect, "cart_num", e);
			},
			
			/**
			 * 点击sku图片打开轮播图
			 */
			showImg(index) {
				console.log(index);
			},
			
			/**
			 * 打开属性加入购物车
			 */
			joinCart: function(e) {
				//是否登录
				if (this.isLogin === false) {
					toLogin();
				} else {
					this.getProdcutDetail(e);
				}
			},
			
			/*
			 * 加入购物车
			 */
			addCart(news) {
				console.log(news);
				let that = this,
					productSelect = that.productValue[that.attrValue];
				that.currentPage = false;
				//打开属性
				if (that.attrValue) {
					//默认选中了属性，但是没有打开过属性弹窗还是自动打开让用户查看默认选中的属性
					that.attr.cartAttr = !that.isOpen ? true : false;
				} else {
					if (that.isOpen) that.attr.cartAttr = true;
					else that.attr.cartAttr = !that.attr.cartAttr;
				}
				//只有关闭属性弹窗时进行加入购物车
				if (that.attr.cartAttr === true && that.isOpen === false)
					return (that.isOpen = true);
				//如果有属性,没有选择,提示用户选择
				if (
					that.attr.productAttr.length &&
					productSelect === undefined &&
					that.isOpen === true
				)
					return that.$util.Tips({
						title: "产品库存不足，请选择其它属性",
					});
				if (that.attr.productSelect.cart_num <= 0) {
					that.attr.productSelect.cart_num = 1;
					that.isOpen = false;
					return that.$util.Tips({
						title: "请先选择数量",
					});
				}
				console.log(that.attr.productSelect);
				// console.log(q)
				if (news) {
					that.isOpen = false;
					that.attr.cartAttr = false;
					uni.navigateTo({
						url: "/pages/goods/order_confirm/index?detail=" + encodeURIComponent(JSON.stringify(productSelect)) +
							"&buyNumber=" +
							that.attr.productSelect.cart_num,
					});
				} else {
					addToCar({
							userInfoId: that.uid,
							proDetailId: productSelect.proDetailId,
							addNumber: that.attr.productSelect.cart_num
						}).then(function(res) {
							that.isOpen = false;
							that.attr.cartAttr = false;
			
							that.$util.Tips({
								title: "添加购物车成功",
								success: () => {
									that.getUserCar(true);
								},
							});
						})
						.catch((err) => {
							that.isOpen = false;
							return that.$util.Tips({
								title: err,
							});
						});
				}
			},
			
			/**
			 * 默认选中规格
			 */
			defaultSelect() {
				let productAttr = this.attr.productAttr;
				let value = [];
				for (var key in this.productValue) {
					value = this.attr.productAttr.length ? key.split(",") : [];
					break;
				}
				for (let i = 0; i < productAttr.length; i++) {
					// this.$set(productAttr[i], "index", value[i]);
					this.$set(productAttr[i], "index", this.productValue[value[i]].specifications);
				}
				let productSelect = this.productValue[value.join(",")];
				if (productSelect && productAttr.length) {
					this.$set(
						this.attr.productSelect,
						"store_name",
						productSelect.productName
					);
					this.$set(this.attr.productSelect, "image", productSelect.productImage);
					this.$set(this.attr.productSelect, "price", productSelect.proxyPrice);
					// if (this.userType == 'STORE') {
					// 	this.$set(this.attr.productSelect, "price", productSelect.productPrice);
					// } else if(this.userType == 'SALE') {
					// 	this.$set(this.attr.productSelect, "price", productSelect.proxyPrice);
					// }
					this.$set(this.attr.productSelect, "cart_num", 1);
					this.$set(this, "attrValue", value.join(","));
					this.$set(this, "attrTxt", "已选择");
				} else if (!productSelect && productAttr.length) {
					this.$set(
						this.attr.productSelect,
						"store_name",
						this.detail.productName
					);
					this.$set(this.attr.productSelect, "image", this.detail.productImage);
					this.$set(this.attr.productSelect, "price", productSelect.proxyPrice);
					// if (this.userType == 'STORE') {
					// 	this.$set(this.attr.productSelect, "price", productSelect.productPrice);
					// } else if(this.userType == 'SALE') {
					// 	this.$set(this.attr.productSelect, "price", productSelect.proxyPrice);
					// }
					this.$set(this.attr.productSelect, "cart_num", 0);
					this.$set(this, "attrValue", "");
					this.$set(this, "attrTxt", "请选择");
				} else if (!productSelect && !productAttr.length) {
					this.$set(
						this.attr.productSelect,
						"store_name",
						this.storeInfo.store_name
					);
					this.$set(this.attr.productSelect, "image", this.detail.productImage);
					this.$set(this.attr.productSelect, "price", productSelect.proxyPrice);
					// if (this.userType == 'STORE') {
					// 	this.$set(this.attr.productSelect, "price", productSelect.productPrice);
					// } else if(this.userType == 'SALE') {
					// 	this.$set(this.attr.productSelect, "price", productSelect.proxyPrice);
					// }
					this.$set(this.attr.productSelect, "cart_num", 1);
					this.$set(this, "attrValue", "");
					this.$set(this, "attrTxt", "请选择");
				}
			},
			
			/**
			 * 获取用户购物车
			 */
			getUserCar() {
				let that = this;
				getUserCar({
					userInfoId: that.uid
				}).then(res => {
					that.CartPrice = 0;
					that.CartCount = 0;
					that.selectValue = [];
					res.value.forEach(e => {
						that.CartPrice = that.$util.$h.Add(that.CartPrice, that.$util.$h.Mul(e.buyNumber, e.productPrice));
						that.CartCount = that.$util.$h.Add(that.CartCount, e.buyNumber);
						that.selectValue.push(e.carId);
					})
				}).catch(err => {
					that.$util.Tips({
						title: err
					});
				})
			},
			
			/**
			 * @param {Object} event
			 * 立即下单
			 */
			subOrder(event) {
				let that = this,
					selectValue = that.selectValue;
					console.log(selectValue)
				if (selectValue.length > 0) {
					uni.navigateTo({
						url: '/pages/goods/order_confirm_cart/index?cartId=' + selectValue.join(',')
					});
				} else {
					return that.$util.Tips({
						title: '请选择产品'
					});
				}
			},
		}
	}
</script>

<style>
	page {
		background: #F3F3F3;
	}

	.container {
		padding-bottom: calc(48px + constant(safe-area-inset-bottom));
		padding-bottom: calc(48px + env(safe-area-inset-bottom));
	}

	.container .a {
		padding: 30rpx 30rpx 0;
		position: relative;
		z-index: 9;
		background-color: #fff;
	}

	.container .a .search {
		padding: 0 20rpx;
		display: flex;
		align-items: center;
		background: #F6F7F9;
		border-radius: 60rpx;
	}

	.container .a .search input {
		background: none;
	}

	.container .tab {
		white-space: nowrap;
		background: #fff;
	}

	.container .tab text {
		padding: 20rpx 0;
		display: inline-block;
		vertical-align: middle;
		position: relative;
		margin-left: 40rpx;
	}

	.container .tab .on {
		font-weight: bold;
		font-size: 36rpx;
		color: #06A972;
	}

	.container .bd .uni-flex {
		align-items: center;
	}

	.container .bd .uni-flex .uni-flex-item {
		font-size: 22rpx;
		color: #E91E1E;
	}

	.container .bd .uni-flex .uni-flex-item text {
		font-size: 32rpx;
	}

	.container .bd .uni-flex image {
		width: 48rpx;
		height: 48rpx;
	}

	.container .bd {
		display: flex;
		flex-wrap: wrap;
		padding: 15rpx;
	}

	.container .bd>view {
		width: 50%;
		box-sizing: border-box;
		padding: 10rpx;
	}

	.container .bd .box {
		background-color: #fff;
		overflow: hidden;
		border-radius: 14rpx;
	}

	.container .bd .dl {
		padding: 15rpx;
	}

	.container .bd .dt {
		font-weight: bold;
		line-height: 40rpx;
	}

	.container .bd .p {
		font-size: 22rpx;
		color: #666;
		padding: 10rpx 0;
	}

	/deep/.uni-numbox__minus,
	/deep/.uni-numbox__plus {
		width: 36rpx;
		height: 36rpx;
		background: #FFFFFF;
		border: 1px solid #06A972;
		border-radius: 50%;
	}

	/deep/.uni-numbox--text {
		font-size: 16px;
	}

	/deep/.uni-numbox__value {
		height: 40rpx;
		border: none;
		min-height: 36rpx;
		width: 50rpx;
	}

	/deep/.uni-numbox {
		width: auto;
		height: auto;
	}

	/deep/.uni-numbox__plus {
		background: #06A972;
	}

	/deep/.uni-numbox__plus .uni-numbox--text {
		color: #fff;
	}

	.bottom {
		font-size: 24rpx;
		line-height: 36rpx;
		position: fixed;
		z-index: 999;
		left: 0;
		bottom: 0;
		padding: 10rpx 30rpx;
		padding-bottom: calc(0rpx + constant(safe-area-inset-bottom));
		padding-bottom: calc(0rpx + env(safe-area-inset-bottom));
		background-color: #fff;
		box-sizing: border-box;
		width: 100%;
	}

	.bottom image {
		width: 60rpx;
		height: 60rpx;
		margin-right: 20rpx;
	}

	.bottom .price {
		color: #E91E1E;
	}

	.bottom button {
		font-size: 28rpx;
		border-radius: 60rpx;
	}
</style>